package com.yuanfeng.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.yuanfeng.commoms.config.WXConfigUtil;
import com.yuanfeng.commoms.config.WXPayConfig;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.PayToolUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.payment.feign.UsermsServiceClient;
import com.yuanfeng.payment.mapper.PayConfigMapper;
import com.yuanfeng.payment.mapper.PayConsumeRecordMapper;
import com.yuanfeng.payment.mapper.PayConsumeTradeBackMapper;
import com.yuanfeng.payment.mapper.PayConsumeTradeMapper;
import com.yuanfeng.payment.service.PayStrategyHandleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Stranger
 * @date 2023/4/13 15:16
 */
@Service
public class WXPayPlusServicesImpl implements PayStrategyHandleService {


    private static PayConfigMapper payConfigMapper;


    private static PayConsumeTradeMapper payConsumeTradeMapper;


    private static PayConsumeTradeBackMapper payConsumeTradeBackMapper;


    private static PayConsumeRecordMapper payConsumeRecordMapper;


    private static UsermsServiceClient usermsServiceClient;

    // 注入的时候，给类的 service 注入
    @Autowired
    public void setUsermsServiceClient(UsermsServiceClient usermsServiceClient) {

        WXPayPlusServicesImpl.usermsServiceClient = usermsServiceClient;
    }

    // 注入的时候，给类的 service 注入
    @Autowired
    public void setMapper(PayConfigMapper payConfigMapper, PayConsumeTradeMapper payConsumeTradeMapper,
                          PayConsumeTradeBackMapper payConsumeTradeBackMapper, PayConsumeRecordMapper payConsumeRecordMapper) {
        WXPayPlusServicesImpl.payConfigMapper = payConfigMapper;
        WXPayPlusServicesImpl.payConsumeTradeMapper = payConsumeTradeMapper;
        WXPayPlusServicesImpl.payConsumeTradeBackMapper = payConsumeTradeBackMapper;
        WXPayPlusServicesImpl.payConsumeRecordMapper = payConsumeRecordMapper;
    }

    final static Logger log = LoggerFactory.getLogger(WXPayPlusServicesImpl.class);

    /**
     * 初始化 阿里云支付参数
     */
    public void initWXPayConfig() {
        //微信 pc  h5
        String paymentMode = "00";
        Map<String, Object> outMap = payConfigMapper.selectPayConfig(paymentMode);
        WXPayConfig.API_KEY = outMap.get("appAPIKey").toString();
        WXPayConfig.APP_SECRET = outMap.get("appSecret").toString();
        WXPayConfig.MCH_ID = outMap.get("appMCHId").toString();
        WXPayConfig.APP_ID = outMap.get("appID").toString();
        WXPayConfig.NOTIFY_URL = outMap.get("notifyUrl").toString();
        WXPayConfig.REDIRECT_URL = outMap.get("redirectUrl").toString();
        WXPayConfig.PLUS_NOTIFY_URL = outMap.get("redirectUrl").toString();
        if(outMap.containsKey("weChatPcPath")){
            WXPayConfig.weChatWapPath=outMap.get("weChatPcPath").toString();
        }


        //微信app
        WXConfigUtil.KEY = outMap.get("appAPIKey").toString();
        WXConfigUtil.APP_SECRET = outMap.get("appSecret").toString();
        WXConfigUtil.MCH_ID = outMap.get("appMCHId").toString();
        WXConfigUtil.APP_ID = outMap.get("appID").toString();
        WXConfigUtil.NOTIFY_URL_APP = outMap.get("notifyUrl").toString();
        //微信小程序
        String paymentMode2 = "02";
        Map<String, Object> outMap2 = payConfigMapper.selectPayConfig(paymentMode2);
        WXPayConfig.Applet_APP_ID = outMap2.get("appID").toString();
        WXPayConfig.Applet_APP_SECRET = outMap2.get("appSecret").toString();


    }

    @Override
    public ResponseResult userPayEntrance(Map<Object, Object> map, HttpServletRequest request, HttpServletResponse response) {
        try {
            String token = (String) map.get("token");
            BigDecimal totalPrice = new BigDecimal(String.valueOf(map.get("payPrice")));

            //创建支付单号
            int i = PayToolUtil.buildRandom(6);
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            StringBuffer plusorder = new StringBuffer("PLUS");
            plusorder.append(format.format(new Date()));
            plusorder.append(i);

            String goodsName = "PLUS订单编号" + plusorder.toString();

            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
            String userId = userInfo.getUserId();


            String payAmount = String.valueOf(totalPrice);
            String price = PayToolUtil.getMoney(payAmount);
            Map<String, String> params = new HashMap<String, String>();
            params.put("appid", WXPayConfig.APP_ID);
            params.put("mch_id", WXPayConfig.MCH_ID);
            params.put("nonce_str", PayToolUtil.create_nonce_str());
            params.put("body", goodsName);
            params.put("attach", JSON.toJSONString(map));
            //开会员需要参数
            params.put("out_trade_no", plusorder.toString());
            params.put("total_fee", price);

            params.put("spbill_create_ip", PayToolUtil.getIpAddr(request));
            params.put("notify_url", WXPayConfig.PLUS_NOTIFY_URL);
            params.put("trade_type", "NATIVE");

            String sign = PaymentKit.createSign(params, WXPayConfig.API_KEY);
            params.put("sign", sign);
            log.info("param{}", JSON.toJSONString(params));
            String xmlResult = PaymentApi.pushOrder(params);

            Map<String, String> result = PaymentKit.xmlToMap(xmlResult);

            String return_code = result.get("return_code");
            String return_msg = result.get("return_msg");
            if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
                return ResponseResult.fail(return_msg);
            }
            String result_code = result.get("result_code");
            if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
                return ResponseResult.fail(return_msg);
            }

            String qrCodeUrl = result.get("code_url");
            return ResponseResult.success(qrCodeUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
    }


}
